﻿using Dynamics.NAV.Metro.Common;
using Okra.Data;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dynamics.NAV.Metro.Data
{
    [Export(typeof(INavGLAccountDataSource))]
    [Shared]
    public class NavGLAccountDataSource : INavGLAccountDataSource
    {
        private IList<NavGLAccount> _glaccounts;
        private NavGLAccountDataListSource _dataListSource;
        private NavCompany _currCompany;

        public NavGLAccountDataSource()
        {
            if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
            {
                _glaccounts = (IList<NavGLAccount>)new List<NavGLAccount>();
                _glaccounts.Add(new NavGLAccount() { Index = 0, Name = "John", No = "1234", Balance = 9019 });
                _glaccounts.Add(new NavGLAccount() { Index = 1, Name = "Brian", No = "5678", Balance = 9019 });
                _glaccounts.Add(new NavGLAccount() { Index = 2, Name = "Jesper", No = "9837", Balance = 9019 });
                _glaccounts.Add(new NavGLAccount() { Index = 3, Name = "Kenneth", No = "893489", Balance = 9019 });
                _glaccounts.Add(new NavGLAccount() { Index = 4, Name = "Michael", No = "9984", Balance = 9019 });
            }
        }

        [Import]
        public IDynamicsNavApi NavApi { get; set; }

        public IList<NavGLAccount> GetGLAccounts()
        {
            if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
                return _glaccounts;

            if (NavApi.CurrentCompany != _currCompany)
            {
                _currCompany = NavApi.CurrentCompany;
                _glaccounts = null;
                _dataListSource = null;
            }

            if (_dataListSource == null)
                _dataListSource = new NavGLAccountDataListSource();

            // Create a single instance of the customer list
            // This can then be shared between multiple view models
            if ((_dataListSource != null) && (_glaccounts == null))
            {
                _glaccounts = (IList<NavGLAccount>)new VirtualizingDataList<NavGLAccount>(_dataListSource);
            }

            return _glaccounts;
        }
    }
}
